<?php

namespace Database\Seeders;

use App\Models\Menus;
use App\Models\Role;
use Carbon\Carbon;
use Illuminate\Database\Seeder;
use DB;

class MenusSeeder extends Seeder
{
    /**
     * 当前自增id
     * @var int
     */
    public $id = 1;

    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // 获取所有管角色
        $roles = app(Role::class)->get();
        $roleMenus = [];
        foreach ($roles as $role) {
            $roleMenus[$role->id] = $role->menus()->pluck('key')->toArray();
        }
        DB::table('menus')->truncate(); // 清空表且新增
        $data = $this->handleResetMap([
            // 后台管理
            ['name' => '首页', 'link' => '/', 'icon' => 'ios-home', 'key' => 'index', 'children' => []],
            ['name' => '后台设置', 'link' => '/admin', 'icon' => 'ios-cog', 'key' => 'set', 'children' => [
                ['name' => '管理员', 'key' => 'admin', 'link' => '/admin'],
                ['name' => '角色', 'key' => 'role', 'link' => '/role'],
                ['name' => '权限', 'key' => 'menus', 'link' => '/permission'],
                ['name' => '目录', 'key' => 'permission', 'link' => '/menus'],
            ]]
        ]);
        // 菜单新增并且绑定
        DB::table('menus')->insert($data);
        // 获取所有分类
        $menus = app(Menus::class)->get(['id', 'key']);
        // 处理代码
        foreach ($roles as $role) {
            if (isset($roleMenus[$role->id])) {
                $cloneMenus = clone($menus);
                $role->menus()->sync($cloneMenus->whereIn('key', $roleMenus[$role->id])->pluck('id')->toArray());
            }
        }
        $ids = app(Menus::class)->pluck('id')->toArray();
        $role = app(Role::class)->find(1);
        $role->menus()->sync($ids);
    }

    /**
     * 堆栈
     * @param $map
     * @param int $pid
     * @param int $weight
     * @param array $data
     * @return array
     */
    public function handleResetMap($map, int $pid = 0, int $weight = 1000, array $data = [])
    {
        foreach ($map as $key => $item) {
            $array = [
                'id' => $this->id,
                'name' => $item['name'],
                'key' => $item['key'],
                'parent_id' => $pid,
                'weight' => $weight,
                'status' => isset($item['status']) ? $item['status'] : 1,
                'link' => isset($item['link']) ? $item['link'] : '',
                'icon' => isset($item['icon']) ? $item['icon'] : '',
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ];
            $this->id += 1; // 新增id值
            $weight -= 50; // 新增id值
            $children = isset($item['children']) ? $item['children'] : [];
            $data[] = $array;
            if (count($children) > 0) {
                $data = $this->handleResetMap($children, $array['id'], 1000, $data);
            }
        }
        return $data;
    }
}
